# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from .forms.fields import GMapField

class CoordinatesField(models.Field):
    def __init__(self, verbose_name=None, *args, **kwargs):
        super(CoordinatesField, self).__init__(*args, **kwargs)
        self.verbose_name = verbose_name
        
    def contribute_to_class(self, cls, name):
        self.name = name
        if self.verbose_name is None and name:
            self.verbose_name = name.replace('_', ' ')
        
        # creating three model fields on the fly
        coordinates = models.CharField(
            blank=self.blank,
            null=self.null,
            max_length=100,
            #editable=False
        )
        coordinates.contribute_to_class(cls, "%s" % name)
        
        latitude = models.FloatField(
            _("%s Latitude") % self.verbose_name,
            blank=self.blank,
            null=self.null,
        )
        latitude.contribute_to_class(cls, "%s_latitude" % name)
        
        longitude = models.FloatField(
            _("%s Longitude") % self.verbose_name,
            blank=self.blank,
            null=self.null,
        )
        longitude.contribute_to_class(cls, "%s_longitude" % name)
        
        setattr(cls, self.name, CoordinatesFieldCreator(self))
        
class CoordinatesFieldCreator(object):
    class Values:
        def __init__(self, coords):
            self.coords = coords
            coords = coords.strip('()')
            lat, lng = coords.split(', ')
            self.latitude = lat
            self.longitude = lng
    
    def __init__(self, field):  
        self.field = field
   
    def __get__(self, obj, type=None):
        if obj is None:  
            raise AttributeError('Can only be accessed via an instance.')  

        coords = obj.__dict__.get("%s" % self.field.name, None)

        return self.Values(coords or "(0, 0)")
   
    def __set__(self, obj, value):  
        print "val", repr(value)
        
        if isinstance(value, tuple) and len(value) == 3:
            setattr(obj, "%s" % self.field.name, value[0])
            setattr(obj, "%s_latitude" % self.field.name, value[1])
            setattr(obj, "%s_longitude" % self.field.name, value[2])
        else:
            try:
                #setattr(obj, "%s" % self.field.name, value)
                value = value.strip('()')
                lat, lng = value.split(', ')
                print lat, lng
                setattr(obj, "%s_latitude" % self.field.name, lat)
                setattr(obj, "%s_longitude" % self.field.name, lng)
            except AttributeError:
                pass
        